package com.laolang.shop.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laolang.shop.common.core.util.AssertUtil;
import com.laolang.shop.common.core.util.SpringUtils;
import com.laolang.shop.modules.sys.entity.SysUser;
import com.laolang.shop.modules.sys.mapper.SysUserMapper;
import com.laolang.shop.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public boolean save(SysUser entity) {
        entity.setCreateTime(LocalDateTime.now());
        entity.setVersion(1);
        return super.save(entity);
    }

    @Override
    public SysUser findByPhone(String phone) {
        return getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhone, phone));
    }

    /**
     * 创建用户账号
     *
     * @param phone    手机号
     * @param pwd      密码
     * @param tenantId 租户id
     * @param type     用户账号类型
     * @return SysUser
     */
    @Override
    public SysUser createSysUser(String phone, String pwd, Long tenantId, Integer type) {
        SysUserService self = getSelf();

        SysUser insert = new SysUser();
        insert.setUsername(phone);
        insert.setNickname(null);
        insert.setSalt(BCrypt.gensalt());
        insert.setPwd(BCrypt.hashpw(pwd, insert.getSalt()));
        insert.setType(type);
        insert.setPhone(phone);
        insert.setEmail(null);
        insert.setAvatar(null);
        insert.setTenantId(tenantId);
        self.save(insert);
        SysUser entity = self.getByPhone(phone);
        AssertUtil.notNull(entity, "添加用户账号失败");
        return entity;
    }

    @Override
    public SysUser getByPhone(String phone) {
        return getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhone, phone));
    }

    public SysUserService getSelf() {
        return SpringUtils.getBean(SysUserService.class);
    }
}
